package com.chzc.fm.duotin.ui.channel;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.chzc.fm.duotin.R;
import com.chzc.fm.duotin.adapter.recyclerview.ChannelGridAdapter;
import com.chzc.fm.duotin.bean.channel.Channel;
import com.chzc.fm.duotin.bean.channel.ChannelType;
import com.chzc.fm.duotin.ui.other.BaseFragment;
import com.chzc.fm.duotin.utils.DuotinTask;
import com.chzc.fm.duotin.utils.GlobalParam;
import com.chzc.fm.duotin.utils.HttpUtil;
import com.chzc.fm.duotin.utils.LogUtil;
import com.chzc.fm.duotin.widget.ObservableScrollView;
import com.chzc.fm.duotin.widget.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.List;

/**
 * Created by BillSinla on 2016/6/23.
 */
public class ChannelFragment extends BaseFragment implements View.OnClickListener{

    private TitleBar titleBar;
    private ImageView ivanchor,ivtopic,ivrank,ivradio;
    private RecyclerView recyclerView;
    private ObservableScrollView scrollView;

    private ChannelGridAdapter gridadpter;

    private static final int REQUEST_CODE2 = 2;
    private static final int REQUEST_CODE1 = 1;

    public String[] ids = new String[22];

    public int[] imglist = new int[]{
            R.drawable.ic_channel_entertaimment,  R.drawable.ic_channel_history,
            R.drawable.ic_channel_heart_emotion,  R.drawable.ic_channel_voice_novel,
            R.drawable.ic_channel_comic,  R.drawable.ic_channel_joke_episode,
            R.drawable.ic_channel_ghost_story, R.drawable.ic_channel_commerce,
            R.drawable.ic_channel_platform,  R.drawable.ic_channel_child_education,
            R.drawable.ic_channel_english_listen, R.drawable.ic_channel_broadcast_play,
            R.drawable.ic_channel_open_class, R.drawable.ic_channel_news,
            R.drawable.ic_channel_sex_life,  R.drawable.ic_channel_story_tell,
            R.drawable.ic_channel_buddhist,  R.drawable.ic_channel_health,
            R.drawable.ic_channel_search,  R.drawable.ic_channel_life,
            R.drawable.ic_channel_it_tech,R.drawable.ic_channel_add
    };
    public String[] titlist = new String[]{
            "娱乐综艺","历史人文","心理情感", "有声小说",
            "相声小品","笑话段子","鬼故事", "商业财经",
            "百家讲坛","亲子教育","英语听力", "广播剧",
            "公开课","新闻时讯","两性生活", "评书",
            "佛经禅理","健康养生","探索发现", "生活百科",
            "IT科技","添加"
    };


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_channel;
    }

    @Override
    protected void initViews() {

        titleBar  = (TitleBar) root.findViewById(R.id.channel_top_tb);
        recyclerView = (RecyclerView) root.findViewById(R.id.channel_hot_rv);
        scrollView = (ObservableScrollView) root.findViewById(R.id.channel_osv);

        ivanchor = (ImageView) root.findViewById(R.id.channel_podcastor_iv);
        ivtopic = (ImageView) root.findViewById(R.id.channel_topic_iv);
        ivrank = (ImageView) root.findViewById(R.id.channel_rank_iv);
        ivradio = (ImageView) root.findViewById(R.id.channel_radio_iv);

        GridLayoutManager manager = new GridLayoutManager(getActivity(),4);
        recyclerView.setLayoutManager(manager);

        //设置RecycleView的焦点为false
        recyclerView.setFocusable(false);

    }

    @Override
    protected void initEvent() {

        ivanchor.setOnClickListener(this);
        ivradio.setOnClickListener(this);
        ivrank.setOnClickListener(this);
        ivtopic.setOnClickListener(this);
    }

    @Override
    protected void initData() {

        getChannelDatas();
    }

    public void getChannelDatas()
    {
        getChannel(new DuotinTask.IRequestCallback() {
            @Override
            public void success(Object object) {

                try {
                    JSONObject root = new JSONObject(object.toString());
                    String error_msg = root.getString("error_msg");
                    if("SUCCESS".equals(error_msg))
                    {
                        LogUtil.w("解析成功");
                        JSONObject data = root.getJSONObject("data");
                        JSONArray categorys = data.getJSONArray("subscribed_categories");
                        final List<Channel> catagoryList = Channel.arrayChannelFromData(categorys.toString());

                        LogUtil.w("categoryList》》》"+ categorys);

                        for (int i = 0 ; i < catagoryList.size() ; i++)
                        {
                            Channel channel = catagoryList.get(i);
                            LogUtil.w("Special.ids" + channel.getId());

                            ids[i] = channel.getId();

                            LogUtil.w("ids[i]>>>>>" + ids[i]);
                        }
                    }

                    initUIdata();

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void error(String msg) {

            }
        });

    }


    public void initUIdata() {

        LogUtil.w("ids[0]" + ids[0]);

        if (GlobalParam.TAG_HOT_VALUE) {
            //把数据组成集合
            for (int i = 0; i < imglist.length; i++) {
                ChannelType type = new ChannelType(ids[i],imglist[i], titlist[i]);
                GlobalParam.toptypeList.add(type);
            }
            GlobalParam.TAG_HOT_VALUE = false;
        }

        LogUtil.w("typeList.size() >>>" + GlobalParam.toptypeList.size());

        titleBar.setLeft(true, R.drawable.ic_action_bar_history);
        titleBar.setRight(false);
        titleBar.setSearchBarVisibilty(true);
        titleBar.setTitleBarVisibility(false,null);

        gridadpter = new ChannelGridAdapter(getActivity(),GlobalParam.toptypeList);
        recyclerView.setAdapter(gridadpter);

        gridadpter.setOnItemClickListener(new ChannelGridAdapter.mItemClickListener() {
            @Override
            public void onItemClick(int position) {


                Intent intent = null;
                if(position != (GlobalParam.toptypeList.size()-1) ) {

                    intent = new Intent(getActivity(), HotChannelActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("channeltype", (Serializable) GlobalParam.toptypeList.get(position));
                    intent.putExtras(bundle);
                    startActivityForResult(intent, REQUEST_CODE1);
                }else
                {
                    intent = new Intent(getActivity(),EditTypeActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("typeList", (Serializable) GlobalParam.toptypeList);
                    intent.putExtras(bundle);
                    startActivityForResult(intent,REQUEST_CODE2);
                }


                Toast.makeText(getActivity(),"position>>>>"+position,Toast.LENGTH_SHORT).show();
                LogUtil.w("typeList.size()>>>" + GlobalParam.toptypeList.size());

            }
        });
    }

    @Override
    public void onClick(View v) {

        Intent intent;
        switch (v.getId())
        {
            case R.id.channel_podcastor_iv:
                intent = new Intent(getActivity(),AnchorActivity.class);
                startActivity(intent);
                break;
            case R.id.channel_topic_iv:
                intent = new Intent(getActivity(),TopicActivity.class);
                startActivity(intent);
                break;
            case R.id.channel_rank_iv:
                intent = new Intent(getActivity(),RankActivity.class);
                startActivity(intent);
                break;
            case R.id.channel_radio_iv:
                intent = new Intent(getActivity(),RadioActivity.class);
                startActivity(intent);
                break;

        }
    }


    public void upDateUi(List<ChannelType> types)
    {
        if(types != null)
        {
            LogUtil.w("更新数据");
            GlobalParam.toptypeList.clear();
            GlobalParam.toptypeList.addAll(types);
            gridadpter.notifyDataSetChanged();
        }
    }



    /**
     * 请求频道页面的数据
     * @param callback
     */
    public void getChannel(DuotinTask.IRequestCallback callback)
    {
        DuotinTask.IRequest request = new DuotinTask.IRequest() {
            @Override
            public Object doRequest() {
                return HttpUtil.doGet(GlobalParam.URL_CHANNEL);
            }
        };
        new DuotinTask(request,callback).execute();
    }


}
